# -*- coding: utf-8 -*-
import pymysql

from ..config_util import mysql_config


class ShopCommentMysqlConnectUtil(object):
    def __enter__(self):
        select_sql = "SELECT shop_id FROM shop_info;"
        insert_sql = (
            "INSERT INTO shop_comment(sku_number, shop_id, user_name, is_vip, user_level, star_level, taste, "
            "environment, serve, average_price, comment_time, favorite_dishes, thumbs_up, comment) "
            "VALUES({sku_number!r}, {shop_id!r}, {user_name!r}, {is_vip}, {user_level}, {star_level}, "
            "{taste!r}, {environment!r}, {serve!r}, {average_price}, {comment_time!r}, {favorite_dishes!r}, "
            "{thumbs_up}, {comment!r});")

        create_sql = """
        CREATE TABLE
        IF
            NOT EXISTS `dp`.`shop_comment` (
            `id` BIGINT ( 20 ) NOT NULL AUTO_INCREMENT COMMENT '主键自增',
            `sku_number` VARCHAR ( 100 ) NOT NULL COMMENT '唯一键：店铺ID + 用户名称 + 评论时间',
            `shop_id` VARCHAR ( 100 ) NOT NULL COMMENT '店铺ID',
            `user_name` VARCHAR ( 100 ) NOT NULL COMMENT '用户名称',
            `is_vip` INT ( 10 ) NULL COMMENT '是否是VIP。 0 否，1 是',
            `user_level` INT ( 10 ) NULL COMMENT '用户级别',
            `star_level` INT ( 10 ) NULL COMMENT '评论星数',
            `taste` VARCHAR ( 100 ) NULL COMMENT '口味',
            `environment` VARCHAR ( 100 ) NULL COMMENT '环境',
            `serve` VARCHAR ( 100 ) NULL COMMENT '服务',
            `average_price` INT ( 10 ) NULL COMMENT '人均消费',
            `favorite_dishes` VARCHAR ( 400 ) NULL COMMENT '喜欢的菜',
            `thumbs_up` INT ( 10 ) NULL COMMENT '点赞数量',
            `comment_time` VARCHAR ( 100 ) NULL COMMENT '评论时间',
            `comment` LONGTEXT NULL COMMENT '评论内容',
            `create_time` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY ( `id` ),
            UNIQUE KEY (`sku_number`)
            ) ENGINE = INNODB CHARACTER 
            SET = utf8 COLLATE = utf8_general_ci COMMENT = '店铺评论';"""

        self.connection = pymysql.connect(**mysql_config)
        self.cursor = self.connection.cursor()

        try:
            self.cursor.execute(create_sql)
            self.connection.commit()
        except Exception as e:
            self.connection.rollback()
            raise Exception(str(e))

        return self.connection, self.cursor, select_sql, insert_sql

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.connection.close()
        self.cursor.close()
